/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.app.client.form.bindings;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.nuxeo.gwt.habyt.app.client.form.FormControl;
import org.nuxeo.gwt.habyt.templates.client.bindings.Helper;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.ListBox;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class ListBoxFactory extends AbstractControlFactory {

    public ListBoxFactory() {
        super("listbox");
    }

    @Override
    protected FormControl createControl(Element element) {
        String name = Helper.getAttribute(element, "name");
        String disabled = Helper.getAttribute(element, "disabled");
        String multi = Helper.getAttribute(element, "multiple");
        String size = Helper.getAttribute(element, "size");
        ListBox w = new ListBox(Boolean.parseBoolean(multi));
        w.setName(name);
        w.setEnabled(!Boolean.parseBoolean(disabled));
        if (size != null) {
            w.setVisibleItemCount(Integer.parseInt(size));
        }
        Element child = Helper.getFirstChildElement(element, "g:item");
        while (child != null) {
            String checked = Helper.getAttribute(child, "checked");
            String value = Helper.getAttribute(child, "value");
            String label = child.getInnerHTML();
            w.addItem(label, value);
            if (Boolean.parseBoolean(checked)) {
                w.setItemSelected(w.getItemCount() - 1, true);
            }
            child = Helper.getNextSiblingElement(child, "g:item");
        }
        return new FormControl(w) {
            @Override
            public String getName() {
                return ((ListBox) getWidget()).getName();
            }

            protected void select(String value) {
                ListBox w = (ListBox) getWidget();
                for (int i = 0, len = w.getItemCount(); i < len; i++) {
                    w.setItemSelected(i, false);
                    if (getItemValue(i).equals(value)) {
                        w.setItemSelected(i, true);
                    }
                }
            }

            protected void select(List<String> value) {
                ListBox w = (ListBox) getWidget();
                HashSet<String> set = new HashSet<String>(value);
                for (int i = 0, len = w.getItemCount(); i < len; i++) {
                    w.setItemSelected(i, false);
                    if (set.contains(getItemValue(i))) {
                        w.setItemSelected(i, true);
                    }
                }
            }

            protected void deselect() {
                ListBox w = (ListBox) getWidget();
                for (int i = 0, len = w.getItemCount(); i < len; i++) {
                    w.setItemSelected(i, false);
                }
            }

            protected String getItemValue(int i) {
                ListBox w = (ListBox) getWidget();
                if (i == -1) {
                    return null;
                }
                String v = w.getValue(i);
                if (v == null || v.length() == 0) {
                    v = w.getItemText(i);
                }
                return v;
            }

            @Override
            public Serializable getValue() {
                ListBox w = (ListBox) getWidget();
                if (w.isMultipleSelect()) {
                    ArrayList<String> list = new ArrayList<String>();
                    for (int i = 0, len = w.getItemCount(); i < len; i++) {
                        if (w.isItemSelected(i)) {
                            list.add(getItemValue(i));
                        }
                    }
                    return list;
                } else {
                    return getItemValue(w.getSelectedIndex());
                }
            }

            @SuppressWarnings("unchecked")
            public void setValue(Serializable value) {
                if (value instanceof List) {
                    select((List<String>) value);
                } else if (value != null) {
                    select(value.toString());
                } else {
                    deselect();
                }
            }
        };
    }

}
